package com.ly.runredis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Configuration
@ConditionalOnClass(RedisTemplate.class)
@ConditionalOnProperty(prefix = "ly.redis", name = "disable", matchIfMissing = true)
public class RunRedisConfig {

    @Value("${spring.redis.host:127.0.0.1}")
    private String host;
    @Value("${spring.redis.port:6379}")
    private int port;
    @Value("${ly.redis.redis-server-cmd:/redis/redis-server.exe}")
    private String redisServerCmd;

    // 定义一个方法, 在配置类启动时执行
    @PostConstruct // 设置组件的初始化方法
    public void init() {
        try {
            // 检查redis是否已经启动
            Jedis jedis = new Jedis(host, port);
            // 连接redis, 如果redis 没有启动, 会抛出异常
            jedis.connect();
            //  如果启动了, 直接关闭
            jedis.close();
            System.out.println("Redis 已经启动了!");
        } catch (Exception e) {
            Thread t = new Thread( ()->{
                // 如果未启动, 则启动redis
                // 获取当前运行时对象
                final Runtime runtime = Runtime.getRuntime();
                // 执行系统命令
                try {
                    // 获取进程对象
                    final Process exec = runtime.exec(redisServerCmd);
                    // 获取该进程的输入流
                    try (InputStream in = exec.getInputStream();
                         // 字节流 转 字符流
                         InputStreamReader ir = new InputStreamReader(in,"gbk");
                         // 缓存字符流, 可以按行读取流
                         BufferedReader br = new BufferedReader(ir);
                    ) {
                        String line;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                        }
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            });
            // 设置精灵线程(守护线程), 必须在 start 之前
            t.setDaemon(true);
            t.start();
        }
    }
}
